package com.jams.goodox.activity.serve.enterprise;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.hangzhou.jin.customview.LoadView;
import com.jams.goodox.BaseFragment;
import com.jams.goodox.R;
import com.jams.goodox.constant.AppConfig;
import com.jams.goodox.entity.resp.PolicyItemListResp;
import com.jams.goodox.net.RetrofitCallbackListener;
import com.jams.goodox.net.services.EnterpriseService;
import com.jams.goodox.utils.CollectionUtils;
import com.jams.goodox.utils.DelayUtils;
import com.jams.goodox.utils.DensityUtil;
import com.jams.goodox.utils.StringUtils;
import com.jams.goodox.widget.RefreshRecyclerView;
import com.jams.goodox.widget.mannger.RefreshLinearLayoutManager;
import com.jams.library.commonAdapter.RecycleCommonAdapter;
import com.jams.library.commonAdapter.RecycleCommonViewHolder;
import com.jams.library.listener.OnRecycleItemClickListener;
import com.jams.library.widget.RecyclerDivider;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import retrofit2.Call;

import static com.jams.goodox.activity.serve.enterprise.EnterprisePolicyDetailActivity.POLICY_ID;


/**
 * 根据EnterprisePolicyActivity
 */
public class EnterprisePolicyFragment extends BaseFragment implements SwipeRefreshLayout.OnRefreshListener {

    @Bind(R.id.lv_load)
    LoadView emptyView;
    @Bind(R.id.refresh)
    RefreshRecyclerView refreshRecyclerView;
    @Bind(R.id.srf)
    SwipeRefreshLayout srf;


    /**
     * 传入的typeid
     */

    private String typeId = "";
    private String mParam2;

    private TextView tvContent;
    private int curPage;

    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    private List<PolicyItemListResp.PolicyItemData.PolicyResultListBean> dataList = new ArrayList<>();
    RecycleCommonAdapter<PolicyItemListResp.PolicyItemData.PolicyResultListBean> mAdapter;

    public EnterprisePolicyFragment() {
        // Required empty public constructor
    }

    public static EnterprisePolicyFragment newInstance(String param1) {
        EnterprisePolicyFragment fragment = new EnterprisePolicyFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);

        fragment.setArguments(args);
        return fragment;
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View contextView = inflater.inflate(R.layout.fragment_party, container, false);
        Bundle args = getArguments();
        typeId = StringUtils.newString(args.getString(ARG_PARAM1));
        ButterKnife.bind(this, contextView);
        setData();
        return contextView;
    }

    /**
     * 数据设置
     */
    private void setData() {
        srf.setOnRefreshListener(this);
        refreshRecyclerView.setLayoutManager(new RefreshLinearLayoutManager(mActivity));
        refreshRecyclerView.setHasFixedSize(true);
        refreshRecyclerView.setItemAnimator(new DefaultItemAnimator());
        mAdapter = new RecycleCommonAdapter<PolicyItemListResp.PolicyItemData.PolicyResultListBean>(mActivity, dataList, R.layout.item_enterprise_policy) {
            @Override
            public void convert(RecycleCommonViewHolder helper, PolicyItemListResp.PolicyItemData.PolicyResultListBean item, int position) {
                setItemData(helper, item);
            }
        };
        //增加headView
        View v = new View(mContext);
        ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, DensityUtil.dp2px(mContext, 8));
        v.setLayoutParams(params);
        mAdapter.setHeaderView(v);

        refreshRecyclerView.setAdapter(mAdapter);
        refreshRecyclerView.addItemDecoration(new RecyclerDivider(//分割线 1px
                mContext,
                LinearLayoutManager.VERTICAL,
                1,
                ContextCompat.getColor(getContext(),
                        R.color.shallow_divider)));
        refreshRecyclerView.setLoadDataListener(new RefreshRecyclerView.LoadDataListener() {
            @Override
            public void onLoadMore() {
                requestData();
            }
        });
        onRefresh();
    }

    /**
     * 设置每个条目的数据
     */
    private void setItemData(RecycleCommonViewHolder helper, final PolicyItemListResp.PolicyItemData.PolicyResultListBean item) {
        helper.setText(R.id.tv_tittle, item.title)
                .setText(R.id.tv_time, item.createTime)
                .setText(R.id.tv_read_number, item.readNum + "");
        helper.setOnItemClickListener(new OnRecycleItemClickListener() {
            @Override
            public void itemClick() {
                Intent i = new Intent(mContext, EnterprisePolicyDetailActivity.class);
                i.putExtra(POLICY_ID, StringUtils.newString(item.id));
                qStartActivity(i);
            }
        });
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    @Override
    public void onRefresh() {
        DelayUtils.doAfterDelay(100, new DelayUtils.DelayDoListener() {
            @Override
            public void doAction() {
                try {
                    if (checkUiIsNull()) {
                        return;
                    }
                    srf.setRefreshing(true);
                    curPage = 1;
                    requestData();
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        });
    }

    private void requestData() {
        enqueue(createCallService(EnterpriseService.class).getPolicyListByPage(typeId, curPage, AppConfig.PagSize), new RetrofitCallbackListener<PolicyItemListResp>() {
            @Override
            public void onSuccess(Call<PolicyItemListResp> call, PolicyItemListResp result) {
                try {
                      /* 滑动过快  SwipeRefreshLayout,RefreshRecyclerView 可能为null,
                       原因:EnterprisePolicyFragment快速切换,执行onDestroyView ,ButterKnife.unbind(this);srf,refreshRecyclerView,emptyView为空*/
                    if (checkUiIsNull()) {
                        return;
                    }
                    srf.setRefreshing(false);
                    refreshRecyclerView.loadMoreComplete();
                    if (result.data != null) {
                        if (curPage == 1) {
                            dataList.clear();
                        }
                        if (result.data.pageInfo == null) {
                            refreshRecyclerView.setCanLoadMore(false);
                        } else {
                            refreshRecyclerView.setCanLoadMore(result.data.pageInfo.hasMore);
                        }
                        dataList.addAll(result.data.resultList);
                        curPage++;
                        refreshRecyclerView.notifyData();
                    }
                    if (!CollectionUtils.hasData(dataList)) {
                        emptyView.loadCompleteNoData(R.mipmap.holder_no_common,R.string.no_content);
                    } else {
                        emptyView.loadComplete();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(String msg) {
                try {
                    if (checkUiIsNull()) {
                        return;
                    }
                    srf.setRefreshing(false);
                    refreshRecyclerView.loadMoreComplete();
                    if (!CollectionUtils.hasData(dataList)) {
                        emptyView.loadCompleteNoData(R.mipmap.holder_no_common,R.string.no_content);
                    } else {
                        emptyView.loadComplete();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }
    //判断控件是否为空
    private boolean checkUiIsNull(){
        return (emptyView == null || srf == null || refreshRecyclerView == null );
    }

}
